package wyu.controller;

import com.dto.Result;
import com.entity.PostBar;
import com.entity.User;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wyu.service.PostService;
import wyu.service.feign.PostBarFeign;
import wyu.service.feign.UserBarFeign;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/post")
public class PostController {
    @Resource
    PostService postService;
    @Resource
    UserBarFeign userBarFeign;
    @Resource
    PostBarFeign postBarFeign;

    @GetMapping("/postNum")
    public Integer getPostNumByBarId(@RequestParam("barId")int barId){
        return postService.getPostNumByBarId(barId);
    }
    @GetMapping("getListBySortType")
    public Result getPostsBySortType(@RequestParam("index") int index, @RequestParam("pageSize") int pageSize,
                                                  @RequestParam("sortType") String accordingTo){
        return postService.getPostsBySortType(index,pageSize,accordingTo);
    }
    @GetMapping("/getUserBar")
    public Result getUserBar(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return Result.fail(605,"用户未登录");
        }
        String uname = user.getUname();
        List<Integer> idList = userBarFeign.getUserBarList(uname);
        List<PostBar> postBarList = postBarFeign.getListByIdList(idList);
        return Result.ok(postBarList);
    }
    @PostMapping("/publish")
    public Result publishPost(@Nullable @RequestParam("files") MultipartFile[] files, @RequestParam("barId") int barId,
                              @RequestParam("title") String title, @RequestParam("content") String content,
                              @RequestParam("pure_content") String pure_content, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return Result.fail(605,"登录异常");
        }
        String uname = user.getUname();
        return postService.publishPost(files,barId,title,content,pure_content,uname);
    }
    @GetMapping("/getPostInfo")
    public Result getPostInfo(@RequestParam("postId")int postId,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        String uName = "";
        if (user!=null){
            uName = user.getUname();
        }
        return postService.getPostInfo(postId,uName);
    }

}
